<?php


class Api
{

    public function index()
    {
        // 获取请求数据
        $request = $this->getRequest();
        if (empty($request)) {
            return $this->json(['code' => 1, 'msg' => 'no request']);
        }

        if ($request) {
            // api_token 验证生成规则： key + 当前时间戳，再 md5 加密
            $key = '12321'; // 约定的一个固定值
            $api_token = md5($key . time());
            if (!empty($request['api_token']) && $api_token === $request['api_token']) {

                // todo 其他
                $value = $request['value'] ?? '';

                return $this->json(['code' => 0, 'msg' => 'success']);
            }
        }

        return $this->json(['code' => 1, 'msg' => 'fail']);
    }

    /**
     * 获取请求数据
     * @return array|mixed
     */
    protected function getRequest()
    {
        $request = [];

        switch ($_SERVER["REQUEST_METHOD"]) {
            case "HEAD":
            case "PUT":
                break;
            case "POST":
                // 获取 post
                if (!$_POST) {
                    // 获取类似微信异步请求
                    $_POST = $this->contentToArray(file_get_contents('php://input'));
                }
                $request = $_POST;
                break;
            case "GET":
            default:
                $request = $_REQUEST;
                break;
        }

        return $request;
    }

    /**
     * 字符串转数组
     * @param $content
     * @return array|mixed
     */
    public function contentToArray($content)
    {
        $output = [];
        // string
        if (is_string($content)) {
            parse_str($content, $output);
        } else {
            // xml
            libxml_disable_entity_loader(true); // 禁止引用外部xml实体
            $xml_string = simplexml_load_string($content, 'SimpleXMLElement', LIBXML_NOCDATA);
            $output = json_decode(json_encode($xml_string), true);
        }

        return $output;
    }

    /**
     * 返回json
     * @param $data
     * @return mixed
     */
    protected function json($data)
    {
        header('Content-Type: application/json;charset=utf-8');
        exit(json_encode($data, JSON_UNESCAPED_UNICODE));
    }
}

return (new Api())->index();